package com.symagic.gesture;

import java.util.ArrayList;

import android.gesture.GesturePoint;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.Pool;

public class SymagicGestureMoveToAction extends Action {

	static final Pool<SymagicGestureMoveToAction> pool = new Pool<SymagicGestureMoveToAction>(
			4, 100) {
		protected SymagicGestureMoveToAction newObject() {
			return new SymagicGestureMoveToAction();
		}
	};

	protected float x;
	protected float y;
	protected float startX;
	protected float startY;
	protected float deltaX;
	protected float deltaY;
	protected float duration;
	protected float invDuration;
	protected float taken = 0;
	protected Actor target;
	protected boolean done;

	public static SymagicGestureMoveToAction $(float x, float y, float duration) {
		SymagicGestureMoveToAction action = pool.obtain();
		action.x = x;
		action.y = y;
		action.duration = duration;
		action.invDuration = 1 / duration;
		return action;
	}

	public SymagicGestureMoveToAction() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void act(float delta) {
		// TODO Auto-generated method stub
		if (target instanceof SymagicGestureView) {
			taken += delta;
			if (taken >= duration) {
				taken = duration;
				done = true;
			}

			SymagicGestureView view = (SymagicGestureView) target;
			float alpha = taken * invDuration;
			view.setAnimationBaseHeight(startY + deltaY * alpha);
		}
	}

	@Override
	public void setTarget(Actor actor) {
		// TODO Auto-generated method stub
		if (actor instanceof SymagicGestureView) {
			SymagicGestureView view = (SymagicGestureView) actor;
			
			float lowHeight = Float.MIN_VALUE;
			ArrayList<GesturePoint> gesturePoints = view.getGestureLogic().getCurrentGesturePoints();
			
			for( int i = 0; i < gesturePoints.size(); i++ ){
				if( lowHeight < gesturePoints.get(i).y ){
					lowHeight = gesturePoints.get(i).y;
				}
			}
			
			this.target = actor;
			this.startX = 0;
			this.startY = 0;
			this.deltaX = 0;
			this.deltaY = lowHeight - ( Gdx.graphics.getHeight() - ( view.y + view.height ) );
			this.taken = 0;
			this.done = false;
		}
	}

	@Override
	public boolean isDone() {
		return done;
	}

	@Override
	public void finish() {
		pool.free(this);
		if (listener != null)
			listener.completed(this);
	}

	@Override
	public Action copy() {
		return $(x, y, duration);
	}

	@Override
	public Actor getTarget() {
		// TODO Auto-generated method stub
		return target;
	}

}
